local cjson = require("cjson")
local ngx_re = require("ngx.re")
local _ = require("resty.wechat.utils.lodash")
local inspect = require("resty.wechat.utils.inspect")

local ngx_req = ngx.req
local ngx_var = ngx.var
local ngx_log = ngx.log
local ngx_print = ngx.print
local ngx_exit = ngx.exit

local function _verify_request_params(params)
  if params.method ~= "GET" then
    return nil, "register not support " .. params.method .. " method"
  end
  if not params.key then
    return nil, "missing key"
  end
  if not params.app_id then
    return nil, "missing app_id"
  end
  if not params.app_secret then
    return nil, "missing app_secret"
  end
  return true
end

local args = ngx_req.get_uri_args()

local uri_list = _.filter(ngx_re.split(ngx_var[1], '/', "jo"), function(x)
  return string.len(x) ~= 0
end)

if (uri_list[1] == "register" ) then

 elseif  (uri_list[1] == "deregister") then


end

ngx_log(ngx.INFO, type(uri_list))
ngx_log(ngx.INFO, inspect(uri_list))
do
  return
end

local params = {
  method = ngx_req.get_method(),
  key = args.key,
  app_id = args.appid,
  app_secret = args.secret,
}

local ok, err = _verify_request_params(params)

ngx.header["Content-Type"] = "application/json"

if not ok then
  ngx_print(cjson.encode({ errmsg = "failed to verify register : " .. err }))
  return ngx_exit(ngx.HTTP_OK)
end

local red = require("resty.wechat.utils.redis"):connect(wechat_config.redis).redis

local key_exist = red:sismember("app_set", params.key)

if key_exist and key_exist == 1 then
  ngx_print(cjson.encode({ errmsg = "app_key:[" .. params.key .. "] has registed!" }))
  return ngx_exit(ngx.HTTP_OK)
end

red:sadd("app_set", params.key)
red:hset("app_data:" .. params.key, "app_id", params.app_id)
red:hset("app_data:" .. params.key, "app_secret", params.app_secret)

ngx_print(cjson.encode({ errmsg = "sucess" }))
return ngx_exit(ngx.HTTP_OK)
